<?php
@set_time_limit(0);
function systemplate($filename,$styledir='msystem',$fileext='.html')
{
	strpos($filename,'..')&&exit('Forbidden!');
	$filepath = MCC_ROOT.'/templates/'.$styledir.'/'.$filename.$fileext;
	if(!file_exists($filepath))
	{
		$filepath = MCC_ROOT.'/templates/msystem/'.$filename.$fileext;
	}
	return $filepath;
}
function numofpage($count,$page,$numofpage,$url,$max=null){

	global $tablecolor;
	$total = $numofpage;
	if(!empty($max)){
		$max = (int)$max;
		$numofpage > $max && $numofpage = $max;
	}
	if($numofpage <= 1 || !is_numeric($page)){
		return '';
	} else{
		list($url,$mao) = explode('#',$url);
		$mao && $mao = '#'.$mao;
		$lastp = $page-1;
		$pages="<a href=\"{$url}page=1\"  class=\"a2\">首页</a> ";
		$pages.= "<a href=\"{$url}page=$lastp\"  class=\"a2\">上一页</a> ";
		for($i=$page-3;$i<=$page-1;$i++){
			if($i<1) continue;
			$pages .= "<a href=\"{$url}page=$i$mao\" class=\"a1\">$i</a> ";
		}
		$pages .= " <a href=\"{$url}page=$page\" class=\"a3\"> $page </a> ";
		if($page < $numofpage){
			$flag = 0;
			for($i=$page+1;$i<=$numofpage;$i++){
				$pages .= "<a href=\"{$url}page=$i$mao\" class=\"a1\">$i</a> ";
				$flag++;
				if($flag==4) break;
			}
		}
		$nextp = $page==$numofpage?$page:$page+1;
		$pages .= "<a href=\"{$url}page=$nextp\"  class=\"a2\">下一页</a>";
		$pages .=" <a href=\"{$url}page=$numofpage\"  class=\"a2\">尾页</a>";
		$pages.="共&nbsp;$numofpage&nbsp;页";
		
		$pages.=" go<input id=ds type=\"text\" style=\" height:18px; width:30px;\" size=\"10\" onkeydown=\"javascript: if(event.keyCode==13){ location='".$url."page='+this.value+'';return false;}\"/> ";
		 //<input style=\"border:#00CCFF solid 1px;height:18px; width:30px;\" type=\"submit\" name=\"Submit\" value=\"转到\" onclick=\"javascript:location='".$url."page='+document.getElementById('ds').value+'';\"/>";
		return $pages;
	}
}
function dsetcookie($var, $value, $life = 0, $prefix = 1) {
	global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
	setcookie(($prefix ? $cookiepre : '').$var, $value,
		$life ? $timestamp + $life : 0, $cookiepath,
		$cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}
function UNcookie($var='')
{
	global $msys_uid,$msys_user,$msys_pw;
	if(!is_array($var))
	{
		setcookie($var,'',-86400*365);
	}
	else 
	{
		foreach ($_COOKIE as $key)
		{
			setcookie($key,'',-86400*365);
		}
	}
	$msys_uid = $adminid = 0;
	$msys_user = $msys_pw =  '';
}
function adminmsg($message,$url_forward='',$istop=0,$ifc=0)
{
	extract($GLOBALS,EXTR_SKIP);
	include MCC_ROOT.'/lang/admincp.lang.php';
	eval("\$message = \"".(isset($lang[$message]) ? $lang[$message] : $message)."\";");
	include MCC_ROOT.'/templates/msystem/ts.html';
	if($url_forward&&$istop!=1)
	{
		echo "<script>

function redirect(url) {

	window.location.replace(url);

}

</script>";
		if(1==$ifc)
		{
			echo "<script>setTimeout(\"redirect('$url_forward&ifcacti=1');\",3000);</script>";
		}
		else 
		{
			echo "<script>setTimeout(\"redirect('$url_forward');\",3000);</script>";
		}
	}
	elseif($url_forward&&$istop==1) 
	{
		echo "<script>

function redirect(url) {

	top.location.replace(url);

}

</script>";
		if(1==$ifc)
		{
			echo "<script>setTimeout(\"redirect('$url_forward&ifcacti=1');\",2000);</script>";
		}
		else 
		{
			echo "<script>setTimeout(\"redirect('$url_forward');\",2000);</script>";
		}	
	}
	exit();
}
function sqldumptable($table, $startfrom = 0, $currsize = 0) {
	global $db, $sizelimit, $startrow, $extendins, $sqlcompat, $sqlcharset, $dumpcharset, $usehex, $complete, $excepttables;

	$offset = 300;
	$tabledump = '';
	$tablefields = array();

	$query = $db->query("SHOW FULL COLUMNS FROM $table", 'SILENT');
	if(!$query && $db->errno() == 1146) {
		return;
	} elseif(!$query) {
		$usehex = FALSE;
	} else {
		while($fieldrow = $db->fetch_array($query)) {
			$tablefields[] = $fieldrow;
		}
	}
	if(!$startfrom) {

		$createtable = $db->query("SHOW CREATE TABLE $table", 'SILENT');

		if(!$db->error()) {
			$tabledump = "DROP TABLE IF EXISTS $table;\n";
		} else {
			return '';
		}

		$create = $db->fetch_row($createtable);

		if(strpos($table, '.') !== FALSE) {
			$tablename = substr($table, strpos($table, '.') + 1);
			$create[1] = str_replace("CREATE TABLE $tablename", 'CREATE TABLE '.$table, $create[1]);
		}
		$tabledump .= $create[1];

		if($sqlcompat == 'MYSQL41' && $db->version() < '4.1') {
			$tabledump = preg_replace("/TYPE\=(.+)/", "ENGINE=\\1 DEFAULT CHARSET=".$dumpcharset, $tabledump);
		}
		if($db->version() > '4.1' && $sqlcharset) {
			$tabledump = preg_replace("/(DEFAULT)*\s*CHARSET=.+/", "DEFAULT CHARSET=".$sqlcharset, $tabledump);
		}

		$query = $db->query("SHOW TABLE STATUS LIKE '$table'");
		$tablestatus = $db->fetch_array($query);
		$tabledump .= ($tablestatus['Auto_increment'] ? " AUTO_INCREMENT=$tablestatus[Auto_increment]" : '').";\n\n";
		if($sqlcompat == 'MYSQL40' && $db->version() >= '4.1' && $db->version() < '5.1') {
			if($tablestatus['Auto_increment'] <> '') {
				$temppos = strpos($tabledump, ',');
				$tabledump = substr($tabledump, 0, $temppos).' auto_increment'.substr($tabledump, $temppos);
			}
			if($tablestatus['Engine'] == 'MEMORY') {
				$tabledump = str_replace('TYPE=MEMORY', 'TYPE=HEAP', $tabledump);
			}
		}
	}
	$excepttables = array();
	if(!in_array($table, $excepttables)) {
		$tabledumped = 0;
		$numrows = $offset;
		$firstfield = $tablefields[0];

		if($extendins == '0') {
			while($currsize + strlen($tabledump) + 500 < $sizelimit * 1000 && $numrows == $offset) {
				if($firstfield['Extra'] == 'auto_increment') {
					$selectsql = "SELECT * FROM $table WHERE $firstfield[Field] > $startfrom LIMIT $offset";
				} else {
					$selectsql = "SELECT * FROM $table LIMIT $startfrom, $offset";
				}
				$tabledumped = 1;
				$rows = $db->query($selectsql);
				$numfields = $db->num_fields($rows);

				$numrows = $db->num_rows($rows);
				while($row = $db->fetch_row($rows)) {
					$comma = $t = '';
					for($i = 0; $i < $numfields; $i++) {
						$t .= $comma.($usehex && !empty($row[$i]) && (strexists($tablefields[$i]['Type'], 'char') || strexists($tablefields[$i]['Type'], 'text')) ? '0x'.bin2hex($row[$i]) : '\''.mysql_escape_string($row[$i]).'\'');
						$comma = ',';
					}
					if(strlen($t) + $currsize + strlen($tabledump) + 500 < $sizelimit * 1000) {
						if($firstfield['Extra'] == 'auto_increment') {
							$startfrom = $row[0];
						} else {
							$startfrom++;
						}
						$tabledump .= "INSERT INTO $table VALUES ($t);\n";
					} else {
						$complete = FALSE;
						break 2;
					}
				}
			}
		} else {
			while($currsize + strlen($tabledump) + 500 < $sizelimit * 1000 && $numrows == $offset) {
				if($firstfield['Extra'] == 'auto_increment') {
					$selectsql = "SELECT * FROM $table WHERE $firstfield[Field] > $startfrom LIMIT $offset";
				} else {
					$selectsql = "SELECT * FROM $table LIMIT $startfrom, $offset";
				}
				$tabledumped = 1;
				$rows = $db->query($selectsql);
				$numfields = $db->num_fields($rows);
				if($numrows = $db->num_rows($rows)) {
					$t1 = $comma1 = '';
					while($row = $db->fetch_row($rows)) {
						$t2 = $comma2 = '';
						for($i = 0; $i < $numfields; $i++) {
							$t2 .= $comma2.($usehex && !empty($row[$i]) && (strexists($tablefields[$i]['Type'], 'char') || strexists($tablefields[$i]['Type'], 'text'))? '0x'.bin2hex($row[$i]) : '\''.mysql_escape_string($row[$i]).'\'');
							$comma2 = ',';
						}
						if(strlen($t1) + $currsize + strlen($tabledump) + 500 < $sizelimit * 1000) {
							if($firstfield['Extra'] == 'auto_increment') {
								$startfrom = $row[0];
							} else {
								$startfrom++;
							}
							$t1 .= "$comma1 ($t2)";
							$comma1 = ',';
						} else {
							$tabledump .= "INSERT INTO $table VALUES $t1;\n";
							$complete = FALSE;
							break 2;
						}
					}
					$tabledump .= "INSERT INTO $table VALUES $t1;\n";
				}
			}
		}

		$startrow = $startfrom;
		$tabledump .= "\n";
	}

	return $tabledump;
}

function submitcheck($var, $allowget = 0) {
	if(empty($GLOBALS[$var])) {
		return FALSE;
	} else {
		global $_SERVER;
		if($allowget || ($_SERVER['REQUEST_METHOD'] == 'POST'&& (empty($_SERVER['HTTP_REFERER']) ||
			preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])))) {
			return TRUE;
		} else {
			adminmsg('submit_invalid');
		}
	}
}

function reg_judge($para,$pvalue)
{
	global $reg_ill;
	$para=trim($para);
	$pvalue=trim($pvalue);
	
	if(array_key_exists($para,$reg_ill))
	{
		//$pvalue==intval($pvalue);
		if(!is_numeric($pvalue)||$pvalue<$reg_ill[$para][0] || $pvalue>$reg_ill[$para][1])
		{
			return -1;
		}
	}
	return 1;
}

function strexists($haystack, $needle) {
	return !(strpos($haystack, $needle) === FALSE);
}
function combin($content,$division='+')
{
	$returninfo = '';
	$content = str_replace("</br>","\r\n",$content);
	$arr = explode("\r\n",$content);
	$arr = array_filter($arr);
	$returninfo = $division.implode("\t",$arr);
	return $returninfo;	
}

function sendInfo($data,$ip='',$port='',$errno='',$errstr='',$timeout='30')
{
	$sock = fsockopen($ip,$port,$errno,$errstr,$timeout);
	if($sock)
	{
		@fputs($sock,$data);
		@fclose($sock);		
	}
}

function addslashes_deep($params)

{
	return is_array($params) ? array_map("addslashes_deep",$params) : addslashes($params);

}

function authcode($string, $operation, $key = '') {
	$key = md5($key ? $key : $GLOBALS['MSYS_AUTH_KEY']);
	$key_length = strlen($key);
	$string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string;
	$string_length = strlen($string);
	$rndkey = $box = array();
	$result = '';
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($key[$i % $key_length]);
		$box[$i] = $i;
	}
	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	if($operation == 'DECODE') {
		if(substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) {
			return substr($result, 8);
		} else {
			return '';
		}
	} else {
		return str_replace('=', '', base64_encode($result));
	}

}

function cutstr($string, $length, $dot = ' ...',$charset='utf-8') {
	if(strlen($string) <= $length) {
		return $string;
	}

	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

	$strcut = '';
	if(strtolower($charset) == 'utf-8') {

		$n = $tn = $noc = 0;
		while($n < strlen($string)) {

			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t <= 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}

			if($noc >= $length) {
				break;
			}

		}
		if($noc > $length) {
			$n -= $tn;
		}

		$strcut = substr($string, 0, $n);

	} else {
		for($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}

	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

	return $strcut.$dot;
}

function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

function order_buildgam($group,$member){
	$temp= $group<<5;
	$gam = $temp | $member;
	return $gam;
}

function order_buildext($flag,$queue,$realext){
	$tempflag = $flag << 15; 
	$tempqueue = $queue << 12; 
	$temp = $tempflag | $tempqueue; 
	$tempext = $temp | $realext; 
	$ext = $tempext; 
	return $ext;
}

function order_set($gam,$ext,$para,$btcip){
	$tempvalue=ut_points(0,8) <<8;
	$tempext1=$ext & $tempvalue;
	$tempext1 >>=8;
	$tempext1++;
	$tempext2=$ext & ut_points(0,8);
	$tempext2++;
	//print $gam.'||'.$tempext1.'||'.$tempext2;
	$tempcon=sprintf("%c%c%c",$gam,$tempext1,$tempext2);
	$tr=chr(7);
	$content=sprintf("%s%s$tr%s",$tempcon,$para,$btcip);
	$content .="\t\t";
	
	//echo $content;exit;
	return $content;
}

function ifopenbtc($gam,$ext,$btcip){
	$tempvalue=ut_points(0,8) <<8;
	$tempext1=$ext & $tempvalue;
	$tempext1 >>=8;
	$tempext1++;
	$tempext2=$ext & ut_points(0,8);
	$tempext2++;
	$tempcon=sprintf("%c%c%c",$gam,$tempext1,$tempext2);
	$content=sprintf("%s%s",$tempcon,$btcip);
	$content .="\t\t";
	//echo $content;exit;
	return $content;
}

function total_order($group,$member,$flag,$queue,$realext,$para,$btcip){
	global $okey;
	$gam=order_buildgam($group,$member);
	$ext=order_buildext($flag,$queue,$realext);
	if(in_array($okey,array('openbtc','offbtc','btcopen')))
	{
		$returndata=ifopenbtc($gam,$ext,$btcip);
	}
	else
	{
		$returndata=order_set($gam,$ext,$para,$btcip);
	}
	//echo $returndata;exit;
	return $returndata;
}

function order_send($para){
	$para=escapeshellarg($para);
	$pip=@popen("/home/CSI $para","r");
	if(!is_resource($pip)){
		exit('popen open failer!');
	}else{
		$reinfo=fgets($pip,1024);
		@pclose($pip);
		/*
		if($reinfo=='0'){
			$pip=@popen("/home/CSI $para","r");
			print $para.'//'; 
			@pclose($pip);
		}
		*/
	}

}
function ut_points($from,$count){
		$from++;
	$sum = 0;
	while($count > 0) // from range get value
	{	
		
		$count--;
		$sum += 2 << $from;
		$from++;
		
	}
	return $sum >> 2; 
}
function prop_getgroup($gam)
{
	$temp = $gam & ut_points(5,3); //get and value
	$group = $temp >> 5; //right move 5 get grou
	//wrong processing:wrong group number
	if ($group == 0)
	{
		print('LOG_ERR, WRONG_GROUP');
		exit();
	}
	
	return $group;
}

function sendemail($toemail,$subject,$message,$additional){
	global $email_config;
	$subject = stripslashes($subject);
	$message = stripslashes($message);
	if($email_config['email_method'] == 1){
		if(@mail($toemail,$subject,$message,$additional)){
			return 1;
		} else{
			return 0;
		}
	} elseif($email_config['email_method'] == 2){
		if(!$fp=@fsockopen($email_config['email_host'],$email_config['email_port'],$errno,$errstr)){
			adminmsg('email_connect_failed');
		}
		if(substr(fgets($fp,512),0,3)!="220"){
			adminmsg('email_connect_failed');
		}
		if($email_config['email_auth']){
			fwrite($fp,"EHLO zhiming\r\n");
			while($rt=strtolower(fgets($fp,512))){
				if(strpos($rt,"-")!==3 || empty($rt)){
					break;
				} elseif(strpos($rt,"2")!==0){
					return false;
				}
			}
			fwrite($fp, "AUTH LOGIN\r\n");
			if(substr(fgets($fp,512),0,3) != 334){
				return false;
			}
			fwrite($fp, base64_encode($email_config['email_user'])."\r\n");
			if(substr(fgets($fp,512),0,3) != 334){
				adminmsg('email_user_failed');
			}
			fwrite($fp, base64_encode($email_config['email_pwd'])."\r\n");
			if(substr(fgets($fp,512),0,3) != 235){
				adminmsg('email_pass_failed');
			}
		} else{
			fwrite($fp, "HELO zhiming\r\n");
		}
		$from = "<$email_config[fromemail]>";
		$from = preg_replace("/.*\<(.+?)\>.*/", "\\1", $from);
		fwrite($fp, "MAIL FROM: <$from>\r\n");
		if(substr(fgets($fp,512),0,3) != 250){
			adminmsg('email_from_failed');
		}
		fwrite($fp, "RCPT TO: <$toemail>\r\n");
		if(substr(fgets($fp,512),0,3) != 250){
			adminmsg('email_toemail_failed');
		}
		fwrite($fp, "DATA\r\n");
		if(substr(fgets($fp,512),0,3) != 354){
			adminmsg('email_data_failed');
		}
		$subject = str_replace("\n",' ',$subject);
		$msg  = "Date: ".Date("r")."\r\n";
		$msg .= "From: \"=?$email_config[email_charset]?B?".base64_encode($email_config['fromuid'])."?=\" <$email_config[fromemail]>\r\n";
		$msg .= "To: \"=?$email_config[email_charset]?B?".base64_encode($email_config['fromusername'])."?=\" <$toemail>\r\n";
		$msg .= "Subject: =?$email_config[email_charset]?B?".base64_encode($subject)."?=\r\n";
		$msg .= "X-mailer: FX mailer\r\n";
		$msg .= "Mime-Version: 1.0\r\n";
		$msg .= "Content-Type: text/html;\r\n";
		$msg .= "\tcharset=\"$email_config[email_charset]\"\r\n";
		$msg .= "Content-Transfer-Encoding: base64\r\n\r\n";
		$msg .= chunk_split(base64_encode($message))."\r\n.\r\n";
		fwrite($fp, $msg);
		fwrite($fp, "QUIT\r\n");
		fclose($fp);
		return true;
	} else{
	}
}
function  dhtmlentities($string)
{
	return htmlentities($string,ENT_COMPAT);
}
?>